//
//  Common.swift
//  flowerpot
//
//  Created by fyname on 15/11/12.
//  Copyright © 2015年 senhe. All rights reserved.
//
import SystemConfiguration.CaptiveNetwork
import NetworkExtension
import Alamofire
import SwiftyJSON
import CryptoSwift

public class Common: NSObject{
    
    static let defaults = NSUserDefaults.standardUserDefaults()
    
    static let UMkey:String = "56557a2467e58e59910005fb"
    
    static let localhost:String = "localhost"
    
    static let key = "secret0key000000"
    static let iv = "0123456789012345"

    
    /**
     * 保存数据
     * key,value
     */
    static func saveData(key:String,value:String){
        defaults.setObject(value, forKey: key)
        defaults.synchronize()
        log.debug("写入数据 key:\(key),value:\(value)")
    }
    
    
    
    
    //获取当前时间
    //格式:yyy-MM-dd HH:mm:ss
    static var getDataTime:String{
        let date = NSDate()
        let timeFormatter = NSDateFormatter()
        timeFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
        timeFormatter.dateFormat = "yyy-MM-dd HH:mm:ss" //(格式可俺按自己需求修整)
        let strNowTime = timeFormatter.stringFromDate(date) as String
        return strNowTime
    }
    
        /**
        * 保存数据
        * key
        */
        static func getData(key:String) -> AnyObject{
            let value = defaults.objectForKey(key)
            log.debug("获取数据 key:\(key),value:\(value)")
            return value!
        }
    
        //显示如「24秒前」、「15分钟前」、「今天 14:15
        static func friendlyTime(dateTime: String) -> String {
        
            let dateFormatter = NSDateFormatter()
            dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
            dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss")
            if let date = dateFormatter.dateFromString(dateTime) {
                    let delta = NSDate().timeIntervalSinceDate(date)
                    
                    if (delta <= 0) {
                       return "刚刚"
                    }
                    else if (delta < 60) {
                       return "\(Int(delta))秒前"
                    }
                    else if (delta < 3600) {
                       return "\(Int(delta / 60))分钟前"
                    }
                    else {
                        let calendar = NSCalendar.currentCalendar()
                        let unitFlags = NSCalendarUnit.NSYearCalendarUnit | NSCalendarUnit.NSMonthCalendarUnit | NSCalendarUnit.NSDayCalendarUnit | NSCalendarUnit.NSHourCalendarUnit | NSCalendarUnit.NSMinuteCalendarUnit
                        let comp = calendar.components(unitFlags, fromDate: NSDate())
                        let currentYear = String(comp.year)
                        let currentDay = String(comp.day)
                        
                        let comp2 = calendar.components(unitFlags, fromDate: date)
                        let year = String(comp2.year)
                        let month = String(comp2.month)
                        let day = String(comp2.day)
                        var hour = String(comp2.hour)
                        var minute = String(comp2.minute)
                        
                        if comp2.hour < 10 {
                            hour = "0" + hour
                        }
                        if comp2.minute < 10 {
                            minute = "0" + minute
                        }
                        
                        if currentYear == year {
                        if currentDay == day {
                            return "今天 \(hour):\(minute)"
                        } else {
                            return "\(month)月\(day)日 \(hour):\(minute)"
                        }
                        } else {
                            return "\(year)年\(month)月\(day)日 \(hour):\(minute)"
                        }
                    }
            }
            return ""
        }
    
    
    /// wifi SSID
    static var WIFISSID: String {
        
        let ns = NEHotspotHelper.supportedNetworkInterfaces()
        
        print(ns)
        
        let interfaces: CFArray? = CNCopySupportedInterfaces()
        if interfaces == nil { return "" }
        
        let if0: UnsafePointer<Void>? = CFArrayGetValueAtIndex(interfaces, 0)
        if if0 == nil { return "" }
        
        let interfaceName: CFStringRef = unsafeBitCast(if0!, CFStringRef.self)
        let dictionary = CNCopyCurrentNetworkInfo(interfaceName) as NSDictionary?
        if dictionary == nil { return "" }
        
        if let SSID = dictionary?[kCNNetworkInfoKeySSID as String] as? String {
            return SSID
        }

        return ""
    }

    static var getSSid:String{
        
        let ne = NEHotspotHelper.supportedNetworkInterfaces()

        var ssid:String = ""
        var bssid:String = ""
        
        for(var i = 0;i<ne.count;i++){
           let ns = ne[i] as! NEHotspotNetwork
            ssid = ns.SSID
            bssid  = ns.BSSID
            print("ssid:\(ssid)")
            print("ssid:\(bssid)")
        }
//        for(ns:NEHotspotNetwork) in ne  {
//              ssid = ns.SSID
//              bssid  = ns.BSSID
//              print("ssid:\(ssid)")
//              print("ssid:\(bssid)")
//        }
//        for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
//            NSString *ssid = hotspotNetwork.SSID;
//            NSString *bssid = hotspotNetwork.BSSID;
//            BOOL secure = hotspotNetwork.secure;
//            BOOL autoJoined = hotspotNetwork.autoJoined;
//            double signalStrength = hotspotNetwork.signalStrength;
//        }
        return "\(ssid)+\(bssid)"
    }
    

    

    //用户登陆
    static func login(username:String,password:String,callback:((isOk: Bool)->Void)) -> Void {
        
        
        let url = "http://localhost:8081/weijia-ccon-site/admin/loginUser"
        let parameter = [
            "username": username,
            "password": password,
        ]
        
        let credential = NSURLCredential(user: username, password: password, persistence: .ForSession)
        
        Alamofire.request(.GET, url, parameters: parameter)
            .authenticate(usingCredential: credential)
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                
                if let rest = response.result.value {
                    print("JSON: \(rest)")
                    let json=JSON(rest)
                    print("JSON: \(json)")
                    let isok = json["infoId"].stringValue
                    log.debug("ok:\(isok)")
                    
                    if (isok == "1"){
                      callback(isOk: true)
                    }else{
                      callback(isOk: false)
                    }
                }
        }

    }
    
    //获取好友信息
    static func gerFriend(groupId:String,callback:((isOk: NSMutableArray)->Void)) -> Void {
        
        
        let url = "http://localhost:8081/weijia-ccon-site/admin/loginUser"
        let parameter = [
            "groupId": groupId
        ]
        
        Alamofire.request(.GET, url, parameters: parameter)
            .responseJSON { response in
                
                if let rest = response.result.value {
                    print("JSON: \(rest)")
                    let json=JSON(rest)
                    print("JSON: \(json)")
                    let isok = json["msgCode"].stringValue
                    log.debug("ok:\(isok)")
                    let emptyDict = NSMutableArray()
                    let friend = FriendDO()
                    if (isok == "666666"){
                        friend.friends_id = json["result"]["friends_id"].stringValue
                        friend.friends_name = json["result"]["friends_name"].stringValue
                        friend.grouping_id = json["result"]["grouping_id"].stringValue
                        emptyDict.addObject(friend)
                        callback(isOk: emptyDict)
                    }else{
                        emptyDict.addObject(friend)
                        callback(isOk: emptyDict)
                    }
                }
        }
        
    }
    
    //圈子列表信息
    static func loadList(positive_id:String,callback:((cb: NSMutableArray)->Void)) {
        
        let url = "http://localhost:8088/weijia-wim-web/friendrelation/getfriendrelation"
        
        let parameter = [
            "positive_id": positive_id
        ]

        Alamofire.request(.GET, url, parameters: parameter)
            .responseJSON { response in
                
                if let text = response.result.value {
                    let json = JSON(text)
                    print(json)
                    let friendRelationDict = NSMutableArray()
                    if(json["msgCode"].stringValue == "666666"){
                        
                        for(var i=0;i<json["result"].count;i++){
                            let friendRelationsDO = FriendRelationsDO()
                            //print("ffffffffffffffffffff")
                            //print(json["result"][i]["passive_id"].stringValue)
                            //print(json["result"][i]["passive_name"].stringValue)
                            //print(json["result"][i]["passive_name"].stringValue)
                            //print("ffffffffffffffffffff")
                            
                            friendRelationsDO.passive_id = json["result"][i]["passive_id"].stringValue
                            friendRelationsDO.passive_name = json["result"][i]["passive_name"].stringValue
                            friendRelationsDO.passive_status = json["result"][i]["passive_status"].stringValue
                            //self.listData.addObject(friendRelationsDO)
                            friendRelationDict.addObject(friendRelationsDO)
                        }
                        
                         callback(cb: friendRelationDict)
                        //self.tableView.reloadData()
                    }
                }
        }
    }
    
    
    static func sendMessageToText(message:String,callback:((isOk: Bool)->Void)) -> Void{
        let url = "http://localhost:8088/weijia-wim-web/message/sendmessage"
        
        /*let headers = [
            "Content-Type": "application/json",
            "dataType":"json"
        ]*/
        
        let parameters = [
            "message_from": "2",
            "message_to": "3",
            "message_content": message,
            "message_status": "0",
            "message_type": "1"
        ]
        

        Alamofire.request(.POST, url, parameters: parameters)
            .responseJSON { response in
                
                if let rest = response.result.value {
                    let text=JSON(rest)
                    print("JSON: \(text)")
                    let isok = text["msgCode"].stringValue
                    if (isok == "666666"){
                        callback(isOk: true)
                    }else{
                        callback(isOk: false)
                    }
                }
        }
    }
    
    static func sendMessageToFile(photoUrl:NSURL,callback:((isOk: Bool)->Void)) -> Void{
        let url = "http://localhost:8088/weijia-wim-web/message/sendfile"
        
        Alamofire.upload(
            .POST,
            url,
            multipartFormData: { multipartFormData in
                multipartFormData.appendBodyPart(fileURL: photoUrl, name: "unicorn")
            },
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON { response in
                        if let rest = response.result.value {
                            let text=JSON(rest)
                            print("JSON: \(text)")
                            let isok = text["msgCode"].stringValue
                            if (isok == "666666"){
                                callback(isOk: true)
                            }else{
                                callback(isOk: false)
                            }
                        }
                    }
                case .Failure(let encodingError):
                    print(encodingError)
                }
            }
        )

    }

     static let cachesDirs = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as NSArray
     static var ff = cachesDirs[0] as! String + "/flowerpot/chat/"
    
    //获取目录名称
    static func getFoldName(foldPath:String)->String{
        
        var sv:String = ""
        
        // 1、初始化
        let fileManager = NSFileManager.defaultManager()
        
        var directory: ObjCBool = ObjCBool(true)
        
        let fs = ff+foldPath
        print("fs:"+fs)
        let exists: Bool = fileManager.fileExistsAtPath(fs, isDirectory: &directory)
        
        if exists && Bool(directory) {
            print("目录已经存在:"+fs)
            sv = fs
        } else  {
            do {
                try fileManager.createDirectoryAtPath(fs, withIntermediateDirectories: true, attributes: nil)
                sv = fs
            } catch {
                print("创建文件夹\(fs),失败")
            }
        }

        return sv
    }
    
    //创建文件夹
    static func DoucumentsCreateFold(pathName:String) -> Bool{
        var flag:Bool = false

        let pathDir = ff + pathName
        
        // 2、初始化
        let fileManager = NSFileManager.defaultManager()

        let isf = fileManager.fileExistsAtPath(pathName)
        if(!isf){
            do {
                try fileManager.createDirectoryAtPath(pathDir, withIntermediateDirectories: true, attributes: nil)
                flag = true
            } catch {
                print("创建文件夹\(pathDir),失败")
            }
        }
        
        return flag
    }
    
     //获取文件夹下的文件
    static func DocumentsGetFold(pathName:String) -> [String] {

        let fileDir = ff + pathName
        
        // 2、初始化
        let fileManager = NSFileManager.defaultManager()
        
        // 5、使用 fileManager 获取目录下的文件名
        let filesList = fileManager.subpathsAtPath(fileDir)
        return filesList!
    }
    
     //删除文件夹
    static func DocumentsDelFold(pathName:String) -> Bool {
        
        var flag:Bool = false

        let fileDir = ff + pathName
        // 2、初始化
        let fileManager = NSFileManager.defaultManager()
        
        // 6、使用 fileManager 删除文件
        do{
          try fileManager.removeItemAtPath(fileDir)
            flag = true
        }catch{
            print("删除\(fileDir),失败")
        }
        
        return flag
    }
    

   
    
    //创建文件
    static func DoucumentsCreateFile(filePath:String,data:NSData) -> Bool{
        
        // 1、获取 Caches 目录
        
        let pathDir = ff + filePath
        
        // 2、初始化
        let fileManager = NSFileManager.defaultManager()

        return fileManager.createFileAtPath(pathDir, contents: data, attributes: nil)
    }
    
    //获取文件夹下的文件
    static func DocumentsGetFile(pathName:String) -> [String] {

        let fileDir = ff + pathName
        
        // 2、初始化
        let fileManager = NSFileManager.defaultManager()
        
        // 5、使用 fileManager 获取目录下的文件名
        let filesList = fileManager.subpathsAtPath(fileDir)
        return filesList!
    }
    
    //删除文件
    static func DocumentsDelFile(pathName:String) -> Bool {
        
        var flag:Bool = false
        
        let fileDir = ff + pathName
        // 2、初始化
        let fileManager = NSFileManager.defaultManager()
        
        // 6、使用 fileManager 删除文件
        do{
            try fileManager.removeItemAtPath(fileDir)
            flag = true
        }catch{
            print("删除\(fileDir),失败")
        }
        
        return flag
    }
    
    
    //创建文件
    static func createFile(foldPath:String, filePath:String,fileContent:String)->Bool{
        
        var flag:Bool = true
        
        let fileManager = NSFileManager.defaultManager()
        
        var isDir : ObjCBool = true
        
        let foldPath = ff + foldPath
        let filePath = foldPath + filePath
        
        //判断目录是否存在
        let isExist = fileManager.fileExistsAtPath(foldPath,isDirectory: &isDir)
        
        if(isExist){
            
            print("flod:"+foldPath)
            print("file:"+filePath)
            
            //创建文件可以通过writeToFile方法将一些对象写入到文件中
            do{
                try fileContent.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
            }catch{
                print("创建txt文件失败")
                flag = false
            }
        }else{
            
            print("flod:"+foldPath)
            print("file:"+filePath)
            
            do
            {
                try fileManager.createDirectoryAtPath(foldPath, withIntermediateDirectories: true, attributes: nil)
            }catch{
                print("创建文件夹失败")
                flag = false
            }
            
            do{
                try fileContent.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
            }catch{
                print("创建txt文件失败")
                flag = false
            }
        }
        
        return flag
    }
    
    //文件移动
    static func moveFile(fileBefore:String,fileAfter:String)->Bool{
        
        var flag:Bool = true
        
        let fileManager = NSFileManager.defaultManager()
        
        
        //判断文件是否存在
        let isExist = fileManager.fileExistsAtPath(fileBefore)
        if(isExist){
            do{
                try fileManager.moveItemAtPath(fileBefore, toPath: fileAfter)
            }catch{
                print("移动文件失败")
                flag = false
            }
        }else{
            flag = false
            print("源文件不存在:"+fileBefore)
        }
        
        return flag
    }
    
    static func getFile(filePath:String,sendId:String,receId:String)->Array<SIMChatMessage>{
        
        var messages = Array<SIMChatMessage>()
        
        var st:[String] = []
        
        var nsd:NSDate = .zero
        
        let fileManager = NSFileManager.defaultManager()
        
        let filePath = ff + filePath
        print("查询目录下文件:"+filePath)
        do{
            st = try NSFileManager.defaultManager().subpathsOfDirectoryAtPath(filePath)
            
            if(st.count>0){
                for(var i=0;i<st.count;i++){
                    
                   let fs = filePath+"/"+st[i]
                    print("文件:"+fs)
                    let data = fileManager.contentsAtPath(fs)
                    let readString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print("文件内容: \(readString)")
                    do{
                        var fileAttributes:[NSObject : AnyObject]? = try fileManager.attributesOfItemAtPath(fs)
                        let modificationDate = fileAttributes![NSFileCreationDate]
                        nsd = modificationDate as! NSDate
                        print(nsd)
                    }catch{
                        print("获取文件属性失败!")
                    }

                    let ff = st[i]
                    print(ff)
                    let sc =  st[i].characters.split {$0 == "$"}.map(String.init)
                    print("******sc******")
                    print(sc[0])
                    print(sc[1])
                    print("******sc******")
                    
                    let sv = sc[1].characters.split {$0 == "."}.map(String.init)
                    
                    print("******sv******")
                    print(sv[0])
                    print(sv[1])
                    print("*******sv*****")
                    
                    if(sv[1] == "txt"){
                        if(sv[0] == sendId){
                            print("发送文本")
                            let sm = SIMChatMessage(SIMChatMessageContentText(text: readString as! String),type: 1)
                            sm.receiveTime = nsd
                            sm.ownership = true
                            messages.append(sm)
                        }else{
                            print("接收文本")
                            let sm = SIMChatMessage(SIMChatMessageContentText(text: readString as! String),type: 1)
                            sm.receiveTime = nsd
                            sm.ownership = false
                            messages.append(sm)
                        }
                        
                    }else if(sv[1] == "png"){
                        let im = UIImage.init(contentsOfFile: fs)
                        
                        if(sv[0] == sendId){
                            print("发送图片")
                            let sm = SIMChatMessage(SIMChatMessageContentImage(origin: im, thumbnail: im),type: 2)
                            sm.receiveTime = nsd
                            sm.ownership = true
                            messages.append(sm)
                        }else{
                            print("接收图片")
                            let sm = SIMChatMessage(SIMChatMessageContentImage(origin: im, thumbnail: im),type: 2)
                            sm.receiveTime = nsd
                            sm.ownership = false
                            messages.append(sm)
                        }
                    }else if(sv[1] == "acc"){
                        let url = NSURL.init(fileURLWithPath: fs)
                        if(sv[0] == sendId){
                            print("发送音频")
                            let sm = SIMChatMessage(SIMChatMessageContentAudio(url: url, duration: 2),type: 3)
                            sm.receiveTime = nsd
                            sm.ownership = true
                            messages.append(sm)
                        }else{
                            print("接收音频")
                            let sm = SIMChatMessage(SIMChatMessageContentAudio(url: url, duration: 2),type: 3)
                            sm.receiveTime = nsd
                            sm.ownership = false
                            messages.append(sm)
                        }
                    }else{
                        print("未知文件类型不错处理...")
                    }
                }
                
            }else{
                print("不存在历史消息")
            }
        
        }catch{
            print("读取历史文件失败!")
        }
        return messages.sort({ $0.receiveTime.compare($1.receiveTime) == NSComparisonResult.OrderedDescending })
    }
    
    
    // Swift 中， static let 才是真正可靠好用的单例模式
    static let screenWidth = UIScreen.mainScreen().bounds.maxX
    static let screenHeight = UIScreen.mainScreen().bounds.maxY
    static let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController as! SliderMenuController
    
    static let homeNavigationController = UIStoryboard(name: "index", bundle: nil).instantiateViewControllerWithIdentifier("indexNavigation") as! UINavigationController
    
    static let mainTabBarController = UIStoryboard(name: "main", bundle: nil).instantiateViewControllerWithIdentifier("main") as! MainTabBarController
    
    static let indexVC = UIStoryboard(name: "index", bundle: nil).instantiateViewControllerWithIdentifier("indexNavigation")
    static let logVC = UIStoryboard(name: "log", bundle: nil).instantiateViewControllerWithIdentifier("logNavigation")
    static let qaVC = UIStoryboard(name: "qa", bundle: nil).instantiateViewControllerWithIdentifier("qaNavigation")
    static let mallVC = UIStoryboard(name: "mall", bundle: nil).instantiateViewControllerWithIdentifier("mallNavigation")
    static let qzVC = UIStoryboard(name: "quanzi", bundle: nil).instantiateViewControllerWithIdentifier("qzNavigation")
    
    static let pcVC = UIStoryboard(name: "pcenter", bundle: nil).instantiateViewControllerWithIdentifier("pcNavigation")
    
    static let menuVC = UIStoryboard(name: "menu", bundle: nil).instantiateViewControllerWithIdentifier("LeftViewController") as! LeftViewController
    
    static let aboutVC = UIStoryboard(name: "menu", bundle: nil).instantiateViewControllerWithIdentifier("aboutNavigation")
    static let deviceVC = UIStoryboard(name: "menu", bundle: nil).instantiateViewControllerWithIdentifier("deviceNavigation")
    static let loginVC = UIStoryboard(name: "login", bundle: nil).instantiateViewControllerWithIdentifier("loginNavigation")
    
}

//自定义弹出窗口
// UIAlertController.showAlert(self, title: "title", message: "message")
// UIAlertController.showAlert(self, title: "title", message: "message", cancelButtonTitle: "cancel", okButtonTitle: "ok")
//UIAlertController.showAlert(self, title: "title", message: "message", cancelButtonTitle: "cancel", okButtonTitle: "ok", okHandler: {
//    (UIAlertAction) in
//    println("no nothing")
//})
extension UIAlertController{
    
    //弹出自定义窗口，无任何时间动作
    class func showAlert(
        presentController:UIViewController!,
        title:String!,
        message:String!,
        cancelButtonTitle:String? = "取消",
        okButtionTitle:String? = "好的"){
        let alert = UIAlertController(title: title!, message: message!, preferredStyle: UIAlertControllerStyle.Alert)
            
            if((cancelButtonTitle) != nil){
                alert.addAction(UIAlertAction(title: cancelButtonTitle!, style: UIAlertActionStyle.Default, handler: nil))
            }
            if((okButtionTitle) != nil){
                alert.addAction(UIAlertAction(title: okButtionTitle!, style: UIAlertActionStyle.Default, handler: nil))
            }
            
            presentController.presentViewController(alert, animated: true, completion: nil)
    }
    
    //弹出自定义窗口，相应自定义动作
    class func showAlertCallBack(
        presentController: UIViewController!,
        title: String!,
        message: String!,
        cancelButtonTitle: String? = "取消",
        okButtonTitle: String? = "好的",
        okHandler: ((UIAlertAction!) -> Void)!) {
            let alert = UIAlertController(title: title!, message: message!, preferredStyle: UIAlertControllerStyle.Alert)
            if (cancelButtonTitle != nil) {
                alert.addAction(UIAlertAction(title: cancelButtonTitle!, style: UIAlertActionStyle.Default, handler: nil))
            }
            if (okButtonTitle != nil) {
                alert.addAction(UIAlertAction(title: okButtonTitle!, style: UIAlertActionStyle.Default, handler: okHandler))
            }
            
            presentController!.presentViewController(alert, animated: true, completion: nil)
    }
}
